const db = wx.cloud.database()
Page({
  data: {
    bookinfo:{},
    goodcount:0
  },

  loadGoodCount(){
    var phone = wx.getStorageSync('phone');
    db.collection('shoppingcart').where({
      phone: phone
    }).get().then(res => {
      console.log("hello")
      console.log(res)
      var total=0
      for(var i=0;i<res.data.length;i++)
        total=total+res.data[i].num
      this.setData({ goodcount: total})
    })
  },

  onLoad: function(options) {
    const bookid = options.id
    db.collection('book').doc(bookid).get().then(res => {
      this.setData({bookinfo:res.data})
    })

  },
  onShow:function(){
    this.loadGoodCount()
  },

  showImg() {
    wx.previewImage({
      urls: [this.data.bookinfo.imgurl],
      current: this.data.bookinfo.imgurl // 当前显示图片的http链接      
    })
  },

  onClickAddgood:function()
  {
    var phone = wx.getStorageSync('phone');
    if (phone == "") {
      wx.navigateTo({
        url: '../login/login'
      })
    }
    else
    {
      var bookinfo = this.data.bookinfo
      bookinfo.phone = phone
      bookinfo.checked = true
      bookinfo.submitdate=db.serverDate()
      bookinfo.num = 1
      delete bookinfo._openid
      delete bookinfo._id
      console.log(bookinfo)

      db.collection('shoppingcart').where({
        isbn: bookinfo.isbn,
        phone:phone
      }).get().then(res => {
        console.log(res)
        if(res.data.length==0)
        {
          db.collection('shoppingcart').add({
            data: bookinfo,
          })
            .then(res => {
              console.log(res)
              this.loadGoodCount()
              wx.showToast({
                title: '添加成功...',
                icon: 'none',
                duration: 1500
              })
            })
            .catch(console.error)
        }
        else
        {
          const _ = db.command
          db.collection('shoppingcart').doc(res.data[0]._id).update({
            data: {
              num: _.inc(1)
            }
          })
            .then(res => {
              this.loadGoodCount()
              console.log(res)
              wx.showToast({
                title: '添加成功...',
                icon: 'none',
                duration: 1500
              })
            })
            .catch(console.error)
        }
      })
    }
  },

  onClickShoppingCart: function (){
    wx.navigateTo({
      url: '../shoppingcart/shoppingcart'
    })
  },
})